/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.demo;

import org.vacoor.nothing.common.misc.util.Platform;
import org.vacoor.nothing.common.util.CommandLineBuilder;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author vacoor
 */
public class ProcessKiller {

    // windows
    public static void kill(int pid, boolean force) throws IOException {
        String[] commands = null;
        if (Platform.isWindows()) {
            // taskkill /pid 进程序号 -t(结束该进程以及所有子进程) -f(强制结束该进程)
            CommandLineBuilder builder = new CommandLineBuilder("taskkill").addArgs("/pid", pid + "");
            if (force) builder.addArg("/f");
            // if (killSub) builder.addArg("/t");

            Process proc = Runtime.getRuntime().exec(builder.getArgsAsArray());
            try{
                Field f = proc.getClass().getDeclaredField("handle");
                f.setAccessible(true);
                long o = (Long) f.get(proc);
                System.out.println(o);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else if (Platform.isMac() || Platform.isX11()) {
            CommandLineBuilder builder = new CommandLineBuilder("kill");
            if (force) builder.addArg("-9");

            Process proc = Runtime.getRuntime().exec(builder.getArgsAsArray());
        } else {
            System.out.println("xxx");
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("hehe");
        kill(209540, false);
//        runMainClassInProcess("org.vacoor.nothing.security.Test", null);
    }
}